package com.xiaolin.io;

import java.io.*;

/**
 * @ClassName TestByteArrayInputStream
 * @Description TODO
 * @Detail detail
 * @Author MyPC
 * @Date 2020/9/26
 * @Version 1.0
 */
public class TestByteArrayInputStream {
    public static void main(String[] args) throws IOException {
        byte[] data = fileToByteArray("D:\\1file\\功能分析.doc");
        boolean b = byteArrayToFile("D:\\1file\\out.doc", data);
        System.out.println(b);
    }

    /**
     * 文件到字节数组
     * @return
     */
    public static byte[] fileToByteArray(String origin){
        FileInputStream fileInputStream= null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            fileInputStream = new FileInputStream(origin);
            byteArrayOutputStream=new ByteArrayOutputStream();
            byte[] fbyte=new byte[1024];
            int len=0;
            while ((len=fileInputStream.read(fbyte))!=-1){
                byteArrayOutputStream.write(fbyte,0,len);
            }
            byteArrayOutputStream.flush();
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fileInputStream !=null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(byteArrayOutputStream !=null){
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 字节数组到文件
     * @param dest
     * @param data
     * @return
     */
    public static boolean byteArrayToFile(String dest,byte[] data){
        FileOutputStream fileOutputStream= null;
        ByteArrayInputStream byteArrayInputStream =null;
        try {
            fileOutputStream = new FileOutputStream(dest);
            byteArrayInputStream= new ByteArrayInputStream(data);
            byte[] in=new byte[1024];
            int len=0;
            while ((len=byteArrayInputStream.read(in))!=-1){
                fileOutputStream.write(in,0,len);
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(byteArrayInputStream !=null){
                try {
                    byteArrayInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fileOutputStream!=null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
}
